package com.fengye.ms.registry.consul.customize;

import com.fengye.ms.registry.core.customizer.MetaCustomizer;
import com.fengye.ms.registry.core.customizer.TagCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistrationCustomizer;

import java.util.*;

/**
 * 自定义实现consul的tag和metadata
 *
 * tag 是字符串
 *
 * metadata是key-value形式的数据
 */
public class RegistrationCustomizer implements ConsulRegistrationCustomizer {

    @Autowired(required = false)
    private final List<TagCustomizer> tagCustomizers = Collections.emptyList();

    @Autowired(required = false)
    private final List<MetaCustomizer> metaCustomizers = Collections.emptyList();

    @Override
    public void customize(ConsulRegistration registration) {
        List<String> tags = registration.getService().getTags();
        if (tags == null) {
            tags = new ArrayList<>();
        }
        System.out.println("自定义tag,数量为:" + tagCustomizers.size());
        for (TagCustomizer tagCustomizer : tagCustomizers) {
            tags.addAll(tagCustomizer.customize());
        }
        registration.getService().setTags(tags);

        Map<String, String> meta = registration.getService().getMeta();
        if (meta == null) {
            meta = new HashMap<>();
        }
        System.out.println("自定义meta,数量为:" + metaCustomizers.size());
        for (MetaCustomizer metaCustomizer : metaCustomizers) {
            meta.putAll(metaCustomizer.customize());
        }

        registration.getService().setMeta(meta);
    }
}
